package com.choose.seat.common.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

public class BeanCopyUtils {

    private static String[] getNumPropertyNames(Object resource){
        BeanWrapper wrapper = new BeanWrapperImpl(resource);
        PropertyDescriptor[] descriptors = wrapper.getPropertyDescriptors();
        Set<String> set = new HashSet<>();
        for(PropertyDescriptor descriptor:descriptors){
            Object value = wrapper.getPropertyValue(descriptor.getName());
            if(value == null) set.add(descriptor.getName());
        }
        String[] result = new String[set.size()];
        return set.toArray(result);
    }

    public static void copyProperties(Object source,Object target,boolean isCopyNull){
        if(isCopyNull)
            BeanUtils.copyProperties(source,target);
        else
            BeanUtils.copyProperties(source,target,getNumPropertyNames(source));
    }
}
